package demon1;

import java.util.Arrays;

public class MyArrayList implements IMyArrayList{
    public int useSize;
    public int[] ele;
    public MyArrayList(){
        this.ele=new int[10];
    }
    public boolean isFull(){
        if(ele.length==useSize){
            return true;
        }
        return false;
    }
    public void checkPos(int pos){
        if(pos<0||pos>useSize){
            throw new PosNotLegalException("pos位置不合法");
        }
    }
    public void Expansion(){
        this.ele= Arrays.copyOf(this.ele,this.ele.length*2);
    }
    @Override
    public void add(int data) {
        if(isFull()){
            Expansion();
        }
        this.ele[useSize]=data;
        useSize++;
    }

    @Override
    public void add(int pos, int data) {
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        if(isFull()){
            Expansion();
        }
        this.ele[pos]=data;
        this.useSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(toFind==this.ele[i]){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if(toFind==this.ele[i]){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        return this.ele[pos];
    }

    @Override
    public void set(int pos, int value) {
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        for (int i = useSize-1; i >pos ; i--) {
            this.ele[i+1]=this.ele[i];
        }
        this.ele[pos]=value;
        this.useSize++;
    }

    @Override
    public void remove(int toRemove) {
        int pos=indexOf(toRemove);
        for (int i = pos; i < useSize-1; i++) {
            this.ele[i]=this.ele[i+1];
        }
        this.useSize--;
    }

    @Override
    public int size() {
        int count=0;
        for (int i = 0; i < this.useSize; i++) {
            count++;
        }
        return count;
    }

    @Override
    public void clear() {
        this.useSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.ele[i]+"");
        }
    }
}
